package com.sports.controller;

import com.sports.entity.Admin;
import com.sports.entity.Athletes;
import com.sports.entity.Judge;
import com.sports.entity.User;
import com.sports.service.AthletesService;
import com.sports.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private AthletesService athletesService;

    /**
     * 登录
     * @param id
     * @param password
     * @param role
     * @param session
     * @return
     */
    @GetMapping("/{id}/{password}/{role}")
    public Map login(@PathVariable Integer id,
                     @PathVariable String password,
                     @PathVariable Integer role, HttpSession session) {
        Map map =new HashMap();
        if (userService.login(id, password, role, session)) {
            map.put("message","success");
        }else{
            map.put("message","fail");
        }

        return map;
    }
    //运动员注册
    @PostMapping("/register")
    public Map register(@RequestBody Athletes athletes) {
        Map map =new HashMap();
        Athletes athletes1 = userService.register(athletes);
        if (athletes1 != null) {
            map.put("message","success");
            map.put("id",athletes1.getAthletesId());
        }else{
            map.put("message","fail");
        }

        return map;

    }
    //获取登陆的用户
    @GetMapping("/getUser")
    public Map<String, Object> getUser(HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        User user = ((User) session.getAttribute("user"));
        if (user == null) {
            map.put("message", "not-login");
        } else {
            if(user instanceof Admin){
                map.put("username", "admin");
            } else if(user instanceof Athletes){
                map.put("username", ((Athletes) user).getAthletesName());
            } else if(user instanceof Judge){
                map.put("username", ((Judge) user).getJudgeName());
            }
            map.put("user", user);
            map.put("role", session.getAttribute("role"));
            map.put("message", "success");
        }
        return map;
    }

    @GetMapping("logout")
    public Map  logout(HttpSession session, HttpServletResponse response) throws IOException {
        session.removeAttribute("user");
        Map map = new HashMap<>();
        map.put("message", "success");
        return  map;
    }
}